<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-08-15 16:45:26
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-12-06 16:49:50
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\Pasture\components\Assets.vue
 * Copyright (c) 2022 by 李天惊 uf_lee@163.com, All Rights Reserved. 
 * 单个牧场-打标资产
-->

<script setup lang="ts">
import { ref, reactive, unref, PropType } from 'vue'
import { ElButton, ElMessageBox } from 'element-plus'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import Transfer from './components/Transfer.vue'
import Record from './components/Record.vue'
import Add from './components/Add.vue'
import { useTable } from '@/hooks/web/useTableTest'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { zcAssetListApi } from '@/api/fa/earcon'
import { spEnclosureListApi, spEnclosureLogOrderAddAdminApi } from '@/api/fa/enclosure'
let registers = ref()
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
// 获取字典
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}
const props = defineProps({
  id: {
    type: Number,
    default: () => null
  },
  dataInfo: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  }
})

const getListAsset = async (val) => {
  val.enclosure_id = props.dataInfo.id
  val.is_die = '0'
  return zcAssetListApi(val)
}
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: getListAsset,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList, setSearchParams } = methods

const loading = ref({
  tree: false,
  save: false
})
const dialogVisible = ref(false)
const dialogTitle = ref('')

registers.value = register

const crudSchemas = reactive<CrudSchema[]>([
  // {
  //   field: 'pasture_org_name',
  //   label: '牧场名称',
  //   width: 220,
  //   search: {
  //     show: true
  //   }
  // },
  {
    field: 'asset_code',
    label: '注射编号',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'asset_code_2',
    label: '项圈编号',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'earcon_code',
    label: '耳标编号',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'breed',
    label: '畜别',
    width: 80,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    }
    // search: {
    //   component: 'Select',
    //   componentProps: {
    //     options: dict.breed,
    //     onChange: breedChange
    //   },
    //   show: true
    // }
  },
  {
    field: 'breed_sub',
    label: '品种',
    width: 120,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    }
    // search: {
    //   component: 'Select',
    //   componentProps: {
    //     options: breedSubData
    //   },
    //   show: true
    // }
  },
  {
    field: 'sex',
    label: '性别',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('animal_sex', cellValue)
    }
    // search: {
    //   component: 'Select',
    //   componentProps: {
    //     options: dict.animal_sex
    //   },
    //   show: true
    // }
  },
  {
    field: 'month_age',
    label: '月龄',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'is_die',
    label: '是否死亡',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('is', cellValue)
    }
  },
  {
    field: 'enclosure_name',
    label: '栏位',
    width: 150
  },
  {
    field: 'new_weight',
    label: '重量（公斤）',
    width: 150
  },
  {
    field: 'purpose',
    label: '用途',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('purpose', cellValue)
    },
    width: 150
  },
  {
    field: 'action',
    width: 250,
    fixed: 'right',
    label: '操作',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])
defineExpose({})

const init = async () => {
  // 列表查询
  await getList()
  await getEnclosure()
}

init()

const { allSchemas } = useCrudSchemas(crudSchemas)

const getRowKey = (row) => {
  return row.id
}

const checkedAll = ref(false)
const selectData = ref([])
const noSelectData = ref([])
const actionType = ref('')

const ids = ref([])

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'out':
      dialogTitle.value = '出栏'
      row.type = '2'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'outSelect':
      if (ids.value.length > 0) {
        ElMessageBox.confirm(`确定出栏${ids.value.length}头资产吗？`, '出栏', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            save('outSelect')
          })
          .catch(() => {})
      } else {
        ElMessageBox.confirm(`暂未选中任何资产，无法出栏？`, '出栏', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {})
          .catch(() => {
            console.log('这里是取消confirm弹框')
          })
      }

      break
    case 'inSelect':
      dialogTitle.value = '入栏'
      row.type = '1'
      dialogVisible.value = true
      break
    case 'transfer':
      dialogTitle.value = '转移栏'
      row.type = '3'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'batch':
      const { getSelections } = methods
      const selections: any = await getSelections()
      checkedAll.value = selections.allCheck.value
      if (selections.allCheck.value) {
        noSelectData.value = selections.noSelectData
        if (selections.noSelectData.value.length > 0) {
          tableObject.currentRow = selections.noSelectData.value[0]
          ids.value = selections.noSelectData.value.map((element) => element.id)
        } else if (selections.selectData.value.length > 0) {
          tableObject.currentRow = selections.selectData.value[0]
        }
      } else {
        if (selections.selectData.value.length > 0) {
          tableObject.currentRow = selections.selectData.value[0]
          ids.value = selections.selectData.value.map((element) => element.id)
        } else if (selections.noSelectData.value.length > 0) {
          tableObject.currentRow = selections.noSelectData.value[0]
        }
        selectData.value = selections.selectData
      }
      if (tableObject.currentRow) {
        dialogTitle.value = '批量操作'
        dialogVisible.value = true
      } else {
        ElMessageBox.alert(`暂未选择资产,请先选择资产？`, '提示', {
          confirmButtonText: '确认',
          type: 'warning'
        }).then(() => {})
      }
      break
    case 'record':
      dialogTitle.value = '资产出入栏记录'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    default:
      console.log('未知类型')
  }
}
const transferRef = ref<ComponentRef<typeof Transfer>>()
const addRef = ref<ComponentRef<typeof Add>>()

const save = async (type: string) => {
  const transfer = unref(transferRef)
  const dataObj = await transfer?.data
  loading.value.save = true
  switch (type) {
    case 'out':
      const resout = await spEnclosureLogOrderAddAdminApi({
        my_dept_id: dataObj.admin_dept_id,
        pasture_org_id: dataObj.pasture_org_id,
        pasture_dept_id: dataObj.pasture_dept_id,
        pasture_user_id: dataObj.pasture_user_id,
        type: dataObj.type,
        date: dataObj.date,
        out_enclosure_id: tableObject.currentRow.enclosure_id,
        in_enclosure_id: dataObj.in_enclosure_id,
        checkedAll: false,
        selected: [dataObj.id]
      })
        .catch(() => {})
        .finally(() => {
          loading.value.save = false
        })
      if (resout) {
        dialogVisible.value = false
        getList()
      }
      break
    case 'save':
      const ressave = await spEnclosureLogOrderAddAdminApi({
        my_dept_id: dataObj.admin_dept_id,
        in_enclosure_id: dataObj.in_enclosure_id,
        pasture_org_id: dataObj.pasture_org_id,
        pasture_dept_id: dataObj.pasture_dept_id,
        pasture_user_id: dataObj.pasture_user_id,
        type: dataObj.type,
        date: dataObj.date,
        out_enclosure_id: dataObj.out_enclosure_id,
        checkedAll: checkedAll.value,
        selected: ids.value
      })
        .catch(() => {})
        .finally(() => {
          loading.value.save = false
        })
      if (ressave) {
        dialogVisible.value = false
        getList()
      }
      break
    case 'transfer':
      const res = await spEnclosureLogOrderAddAdminApi({
        my_dept_id: dataObj.pasture_dept_id,
        pasture_org_id: dataObj.pasture_org_id,
        pasture_dept_id: dataObj.pasture_dept_id,
        pasture_user_id: dataObj.pasture_user_id,
        type: dataObj.type,
        date: dataObj.date,
        out_enclosure_id: dataObj.out_enclosure_id,
        in_enclosure_id: dataObj.in_enclosure_id,
        checkedAll: false,
        selected: [dataObj.id]
      })
        .catch(() => {})
        .finally(() => {
          loading.value.save = false
        })
      if (res) {
        dialogVisible.value = false
        getList()
      }
      break
    case 'inSelect':
      loading.value.save = false
      const add: any = unref(addRef)
      const dataAddObj = await add?.data
      const { getSelections } = add?.methods
      let selectDataInfo = ref({})
      await getSelections().then((res) => {
        selectDataInfo.value = res
        checkedAll.value = res.allCheck.value
        if (res.allCheck.value) {
          if (res.noSelectData.value.length > 0) {
            ids.value = res.noSelectData.value.map((element) => element.id)
          }
        } else {
          if (res.selectData.value.length > 0) {
            ids.value = res.selectData.value.map((element) => element.id)
          }
        }
      })
      const resIn = await spEnclosureLogOrderAddAdminApi({
        my_dept_id: dataAddObj.admin_dept_id,
        pasture_org_id: dataAddObj.pasture_org_id,
        pasture_dept_id: dataAddObj.pasture_dept_id,
        pasture_user_id: dataAddObj.pasture_user_id,
        type: dataAddObj.type,
        date: dataAddObj.date,
        out_enclosure_id: dataAddObj.out_enclosure_id,
        in_enclosure_id: dataAddObj.in_enclosure_id,
        checkedAll: checkedAll.value,
        selected: ids.value
      })
        .catch(() => {})
        .finally(() => {
          loading.value.save = false
        })
      if (resIn) {
        dialogVisible.value = false
        getList()
      }
      break
    default:
      console.log('未知类型')
  }
}
const enclosureData = ref([])
const getEnclosure = async () => {
  const res = await spEnclosureListApi({ id: props.id })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    enclosureData.value = res.data
  }
}
</script>

<template>
  <div>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <div class="mb-10px">
      <ElButton type="primary" @click="action('batch')">批量操作</ElButton>
      <ElButton type="success" @click="action('inSelect')">入栏</ElButton>
    </div>
    <TableSelect
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :row-key="getRowKey"
      :selection="true"
      highlight-current-row
    >
      <template #action="{ row }">
        <ElButton type="primary" @click="action('out', row)">出栏</ElButton>
        <ElButton type="danger" @click="action('transfer', row)">转移栏</ElButton>
        <ElButton type="warning" @click="action('record', row)">记录</ElButton>
      </template>
    </TableSelect>
    <!-- 弹窗 -->
    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <Transfer
        ref="transferRef"
        :data="enclosureData"
        :dataInfo="props.dataInfo"
        :current-row="tableObject.currentRow"
        v-if="
          actionType == 'transfer' ||
          actionType == 'transferSelect' ||
          actionType == 'out' ||
          actionType == 'batch'
        "
      />
      <Add
        v-if="actionType == 'inSelect'"
        :data="enclosureData"
        ref="addRef"
        :dataInfo="props.dataInfo"
        :id="Number(props.id)"
      />
      <Record v-if="actionType == 'record'" :id="Number(tableObject.currentRow.id)" />
      <template #footer>
        <ElButton
          v-if="actionType == 'batch'"
          type="primary"
          :loading="loading.save"
          @click="save((actionType = 'save'))"
        >
          保存
        </ElButton>
        <ElButton
          v-if="actionType == 'out'"
          type="primary"
          :loading="loading.save"
          @click="save(actionType)"
        >
          出栏
        </ElButton>
        <ElButton
          v-if="actionType == 'inSelect'"
          type="primary"
          :loading="loading.save"
          @click="save(actionType)"
        >
          入栏
        </ElButton>
        <ElButton
          v-if="actionType == 'transfer' || actionType == 'transferSelect'"
          type="primary"
          :loading="loading.save"
          @click="save(actionType)"
        >
          转移栏
        </ElButton>
        <ElButton @click="dialogVisible = false">关闭</ElButton>
      </template>
    </Dialog>
  </div>
</template>
<style lang="less" scoped></style>
